<?php

namespace app\common\model;

use think\Model;

/**
 * 刷题次数记录
 */
class QuestionErrorNum extends Model
{
    // 表名
    protected $name = 'question_error_num';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 记录用户进入错题本
     * @param int $user_id 用户ID
     * @return bool
     */
    public static function recordErrorBookAccess($user_id)
    {
        try {
            // 查询今天是否已有记录
            $today = strtotime(date('Y-m-d'));
            $record = self::where([
                'user_id' => $user_id,
                'createtime' => ['>=', $today]
            ])->find();
            if ($record) {
                // 今天已有记录，更新次数
                $result = self::where('id', $record['id'])->update([
                    'num' => $record['num'] + 1,
                    'updatetime' => time()
                ]);
            } else {
                // 今天没有记录，创建新记录
                $result = self::create([
                    'user_id' => $user_id,
                    'num' => 1,
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
            }
            return $result ? true : false;
        } catch (\Exception $e) {
            // 记录日志
            \think\Log::error('记录刷题次数失败: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * 获取用户今天的刷题次数
     * @param int $user_id 用户ID
     * @return int
     */
    public static function getTodayErrorBookCount($user_id)
    {
        $today = strtotime(date('Y-m-d'));
        $record = self::where([
            'user_id' => $user_id,
            'createtime' => ['>=', $today]
        ])->find();

        return $record ? $record['num'] : 0;
    }

    /**
     * 获取用户总刷题次数
     * @param int $user_id 用户ID
     * @return int
     */
    public static function getTotalErrorBookCount($user_id)
    {
        return self::where('user_id', $user_id)->sum('num');
    }

  
} 